package org.groupg.demo.sshd;

import org.apache.commons.io.FileUtils;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.sftp.client.SftpClient;
import org.apache.sshd.sftp.client.SftpClientFactory;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;

public class SftpClientExample {
    public static void main(String[] args) throws Exception {
        SshClient client = SshClient.setUpDefaultClient();
        client.start();

        try (ClientSession session = client.connect("username", "hostname", 22)
                .verify(5000, TimeUnit.MILLISECONDS)
                .getSession()) {

            session.addPasswordIdentity("password");
            session.auth().verify(5000, TimeUnit.MILLISECONDS);

            SftpClientFactory factory = SftpClientFactory.instance();
            try (SftpClient sftp = factory.createSftpClient(session)) {
                // 列出目录内容
                for (SftpClient.DirEntry entry : sftp.readDir("/remote/path")) {
                    System.out.println(entry.getFilename());
                }

                // 下载文件
                Path localFile = Paths.get("/local/path/file.txt");

                try (InputStream read = sftp.read("/remote/path/file.txt")) {
                    StreamUtils.copy(read, Files.newOutputStream(localFile));
                };

                // 上传文件
                Path uploadFile = Paths.get("/local/path/upload.txt");
                sftp.put(uploadFile, "/remote/path/upload.txt");
            }
        } finally {
            client.stop();
        }
    }
}
